package com.team.instantsharing.folder

import org.springframework.web.client.RestTemplate;

import com.team.instantsharing.dto.Folder;
import com.team.instantsharing.dto.FolderSharing;
import com.team.instantsharing.dto.Message;
import com.team.instantsharing.ultils.Constant;
import com.team.instantsharing.ultils.ServiceRequest;
import com.sun.xml.internal.org.jvnet.staxex.Base64Encoder
import grails.converters.JSON

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import org.apache.commons.codec.binary.Base64;

import com.sun.beans.finder.SignatureException

import grails.converters.JSON

class FolderController {

    def createFolder(){
		String folderName = params.folderName;
		String folderPath = params.folderPath;
		
		Folder folder = new Folder();
		folder.setFolderName(folderName);
		folder.setFolderPath(folderPath);
		folder.setUserEmail(session.userEmail);
		folder.setFolderPermission(Constant.DOCUMENT_PRIVATE);
		
		RestTemplate restTemplate = new RestTemplate();
		Message message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.CREATE_FOLDER, folder, Message.class);

		render ([info:message.response] as JSON)
	}
	def shareFolder1(){
		String folderUrl = params.folderUrl;
		println "FolderURL: " + folderUrl;
		
		render view:"/errorPage/errorConstruction.gsp";
	}
	
	def shareFolderToListUser(){
		String folderUrl = params.folderUrl;
		String listEmails = params.listEmails;
		String shareMessage = params.shareMessage;
		println folderUrl + " - " + listEmails;
		Message message = new Message("Error");
		if (!listEmails.isEmpty() && !folderUrl.isEmpty()){
			
			FolderSharing folderSharing = new FolderSharing();
			folderSharing.setFolderUrl(folderUrl);
			folderSharing.setUserEmail(session.userEmail);
			folderSharing.setShareMessage(shareMessage);
			folderSharing.setListUserEmailShared(listEmails);
			
			RestTemplate restTemplate = new RestTemplate();
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.SHARE_FOLDER_TO_USER, folderSharing, Message.class);
		}
		render ([info:message.response] as JSON)
	}
	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
	
	public static String generateHMAC(String data, String secretKey)throws java.security.SignatureException {
		String resultSigningKey = null;
		try {
			SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(),HMAC_SHA1_ALGORITHM);
			Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(data.getBytes());
			resultSigningKey = new String(Base64.encodeBase64(rawHmac));
		} catch (Exception e) {
			throw new SignatureException("Failed to generate HMAC : "+ e.getMessage());
		}
		return resultSigningKey;
	}
	
	def shareFolder(){
		
		String folderUrl = params.folderUrl;
		RestTemplate restTemplate = new RestTemplate();
		Folder folderDownload = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.DOWNLOAD_FOLDER + Constant.SUFFIX + folderUrl, Folder.class);
		
		if (folderDownload.getFolderName() == null){
			render view:"/errorPage/error404.gsp";
			return
		}
		else{
			String folderPath;
			if(folderDownload.getFolderPath().equals('')){
				folderPath = folderDownload.getFolderName();
			}else{
				folderPath = folderDownload.getFolderPath() + Constant.SUFFIX + folderDownload.getFolderName()
			}
			
			def result = [
			 folderName: folderDownload.getFolderName(),
			 folderPath: folderPath,
			 folderOwner : URLEncoder.encode(folderDownload.getUserEmail(), "UTF-8")
			 ]
			render(view: "shareFolder", model: [data: result as JSON])
		}
	}
	
	def shareLinkFolder(){
		
		String path = params.path;
		if (path == null || path == "" || path == "undefined"){
			path = "";
		}
		String trashStatus = params.trashStatus;
		if (trashStatus == null || trashStatus == "" || trashStatus == "undefined"){
			trashStatus = "false";
		}
		String userEmail = params.userEmail;
		
		/*if (session.userEmail.equals(userEmail)){
			redirect controller:'manage', action: 'index';
			return;
		}*/
		
		RestTemplate restTemplate = new RestTemplate();
		String listDocuments = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.GET_LIST_DOCUMENT + "?userEmail=" + userEmail + "&path=" + path + "&trashStatus=" + trashStatus, String.class);
		render(listDocuments) as JSON
		
	}
	
	def leaveUnshareFolder(){
		String userEmailOfRequester = session.userEmail;
		String folderName = params.folderName;
		String folderPath = params.folderPath;
		
		RestTemplate restTemplate = new RestTemplate();
		Message message = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.UNSHARE_FOLDER + "?userEmailOfRequester=" + userEmailOfRequester + "&folderName=" + folderName + "&folderPath=" + folderPath, Message.class);
		
		render ([info:message.response] as JSON)
	}
}
